<?php

/**
 * module_controller.php
 *
 * @copyright  2017 opencart.cn - All Rights Reserved
 * @link       http://www.guangdawangluo.com
 * @author     Edward Yang <yangjin@opencart.cn>
 * @created    3/3/17 14:53
 * @modified   3/3/17 14:53
 */
class ModuleController extends Controller
{
    private $error = array();
    private $data = array();
    protected $route = '';
    protected $moduleName = '';
    protected $template = 'extension/module/common.tpl';
    protected $textItems = ['edit', 'enabled', 'disabled', 'button_grey', 'button_blue', 'yes', 'no'];
    protected $entryItems = array();
    protected $helpItems = array();
    protected $buttonItems = ['save', 'cancel', 'module_add', 'remove'];

    public function __construct($registry)
    {
        parent::__construct($registry);
        if (!$this->route) {
            $this->route = $this->getRoute();
        }
        if (!$this->moduleName) {
            $this->moduleName = $this->getModuleName();
        }
        $this->data['module_name'] = $this->moduleName;
        $this->load->language('extension/module/common');
        $this->load->language($this->route);
        $this->load->model('setting/setting');
    }

    public function index()
    {
        $this->saveSetting();
        $this->setTitle();
        $this->setTextLanguages();
        $this->setEntryLanguages();
        $this->setHelpLanguages();
        $this->setButtonLanguages();
        $this->setErrorData();
        $this->setBreadcrumbs();
        $this->setLinks();
        $this->setFormData();
        $this->setLayouts();
        $this->response->setOutput($this->load->view($this->template, $this->data));
    }

    protected function saveSetting()
    {
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $this->model_setting_setting->editSetting($this->getModuleName(), $this->request->post);
            $this->session->data['success'] = $this->language->get('text_success');
            $this->response->redirect($this->url->link('extension/extension', 'type=module&token=' . $this->session->data['token'], 'SSL'));
        }
    }

    protected function setTitle()
    {
        $this->document->setTitle($this->getHeadingTitle());
    }

    protected function setTextLanguages()
    {
        $this->data['heading_title'] = $this->getHeadingTitle();
        if (empty($this->textItems)) {
            return false;
        }
        foreach ($this->textItems as $item) {
            $this->data['text_' . $item] = $this->language->getDefault('text', $item);
        }
    }

    protected function setEntryLanguages()
    {
        $this->data['entry_status'] = $this->language->getDefault('entry', 'status');
        foreach ($this->entryItems as $item) {
            $this->data['entry_' . $item] = $this->language->getDefault('entry', $item);
        }
        $this->data['entries'] = $this->entryItems;
    }

    protected function setHelpLanguages()
    {
        if (empty($this->helpItems)) {
            return false;
        }
        foreach ($this->helpItems as $item) {
            $this->data['help_' . $item] = $this->language->getDefault('help', $item);
        }
    }

    protected function setButtonLanguages()
    {
        if (empty($this->buttonItems)) {
            return false;
        }
        foreach ($this->buttonItems as $item) {
            $this->data['button_' . $item] = $this->language->getDefault('button', $item);
        }
    }

    protected function setErrorData()
    {
        $this->data['error_warning'] = array_get($this->error, 'warning', '');
        foreach ($this->entryItems as $field) {
            $this->data['error_' . $field] = array_get($this->error, $field, '');
        }
    }

    protected function setBreadcrumbs()
    {
        $this->data['breadcrumbs'] = array();
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_extension'),
            'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', 'SSL')
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->getHeadingTitle(),
            'href' => $this->url->link($this->getRoute(), 'token=' . $this->session->data['token'], 'SSL')
        );
    }

    protected function setLinks()
    {
        $this->data['action'] = $this->url->link($this->getRoute(), 'token=' . $this->session->data['token'], 'SSL');
        $this->data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', 'SSL');
    }

    protected function setFormData()
    {
        foreach ($this->entryItems as $item) {
            $field = $this->getModuleName() . '_' . $item;
            $defaultFromGet = $this->config->get($field);
            $this->data[$field] = array_get($this->request->post, $field, $defaultFromGet);
        }
        $statusField = $this->getModuleName() . '_status';
        $defaultStatusFromGet = $this->config->get($statusField);
        $this->data[$statusField] = array_get($this->request->post, $this->getModuleName() . '_status', $defaultStatusFromGet);
    }

    protected function setLayouts()
    {
        $this->data['header'] = $this->load->controller('common/header');
        $this->data['column_left'] = $this->load->controller('common/column_left');
        $this->data['footer'] = $this->load->controller('common/footer');
    }


    protected function getRoute()
    {
        if ($this->route) {
            return $this->route;
        }
        $route = array_get($this->request->get, 'route');
        if (!$route) {
            throw new \Exception('Empty route!');
        }
        $routes = explode('/', $route);
        if (count($routes) < 2) {
            throw new \Exception('Invalid route');
        }
        return $routes[0] . '/' . $routes[1] . '/' . $routes[2];
    }

    protected function getModuleName()
    {
        if ($this->moduleName) {
            return $this->moduleName;
        }
        $route = $this->getRoute();
        $routes = explode('/', $route);
        return end($routes);
    }

    protected function getHeadingTitle()
    {
        if ($this->language->get('heading_title') != 'heading_title') {
            return $this->language->get('heading_title');
        }
        return studlyCase($this->getModuleName());
    }


    protected function validate()
    {
        if (!$this->user->hasPermission('modify', $this->getRoute())) {
            $this->error['warning'] = $this->language->get('ast_error_access');
        }
        return !$this->error;
    }

    public function install()
    {
    }

    public function uninstall()
    {
    }
}
